package com.frontop.terminal.component;

import com.frontop.terminal.constant.InterfaceConst;
import com.frontop.terminal.entity.TerminalConfig;
import com.frontop.terminal.util.ReadDataUtil;
import javafx.application.Application;
import javafx.concurrent.Worker.State;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.util.Objects;

/**
 * @author CCC
 */
public class Browser extends Application implements Runnable {

    @Override
    public void start(final Stage stage) {
        //判断配置文件是否初始化，已初始化启动时打开播放器
        TerminalConfig terminalConfig = ReadDataUtil.getTerminalConfig();

        //浏览器是否隐藏
        assert terminalConfig != null;
        if (terminalConfig.isBrowserHide()) {
            //最小化
            stage.setIconified(true);
        }

        //浏览器启动时最小化
        if (terminalConfig.isBrowserFullScreen()) {
            //全屏无边框
            stage.setMaximized(true);
            stage.initStyle(StageStyle.TRANSPARENT);
        } else {
            stage.setWidth(1500);
            stage.setHeight(855);
        }

        Scene scene = new Scene(new Group());


        final WebView browser = new WebView();
        final WebEngine webEngine = browser.getEngine();

        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(browser);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);

        webEngine.getLoadWorker().stateProperty()
                .addListener((ov, oldState, newState) -> {

                    if (newState == State.SUCCEEDED) {
                        stage.setTitle(webEngine.getLocation());
                    }

                });

        //网址
        String url = InterfaceConst.LOCAL_TERMINAL_CONFIG;
        //获取是否已经配置过文件来决定打开配置页还是首页
        if (Objects.nonNull(terminalConfig.getStatus()) && terminalConfig.getStatus()) {
            url = InterfaceConst.LOCAL_TERMINAL_HOMEPAGE;
        }

        webEngine.load(url);
        scene.setRoot(scrollPane);
        stage.setScene(scene);
        stage.show();
    }

    @Override
    public void run() {
        launch();
    }
}
